<template>
  <div class="task-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>任务列表</span>
          <el-button type="primary" @click="goToCreate"> 新建任务 </el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="taskList" style="width: 100%">
        <el-table-column prop="taskId" label="任务ID" width="200" />
        <el-table-column prop="taskName" label="任务名称" />
        <el-table-column prop="dbType" label="数据库类型" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              :disabled="row.status !== 'success'"
              @click="handleViewResult(row)"
            >
              查看
            </el-button>
            <el-button
              size="small"
              type="primary"
              :disabled="row.status !== 'success'"
              @click="handleExport(row, 'html')"
            >
              导出
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 文档预览对话框 -->
    <el-dialog v-model="resultVisible" title="文档预览" width="90%" fullscreen>
      <div class="result-actions">
        <el-button v-if="currentTask" @click="handleExport(currentTask, 'md')">
          导出Markdown（推荐）
        </el-button>
        <el-button v-if="currentTask" @click="handleExport(currentTask, 'html')">
          导出HTML
        </el-button>
        <el-button @click="resultVisible = false">关闭</el-button>
      </div>
      <div v-if="resultHtml" class="document-preview" v-html="resultHtml"></div>
      <el-empty v-else description="暂无文档内容" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDocumentStore } from '@/stores/document'
import { getStatusText, getStatusColor, formatTime } from '@/utils/task'
import type { DocumentTask } from '@/types/document'

const router = useRouter()
const documentStore = useDocumentStore()

const loading = ref(false)
const resultVisible = ref(false)
const currentTask = ref<DocumentTask | null>(null)

const { taskList } = storeToRefs(documentStore)

const pagination = ref({
  current: 1,
  size: 10,
  total: 0,
})

// 加载任务列表
const loadTaskList = async () => {
  loading.value = true
  try {
    const response = await documentStore.fetchTaskList({
      page: pagination.value.current,
      size: pagination.value.size,
    })
    pagination.value.total = response.total
  } catch (error: any) {
    ElMessage.error(`加载任务列表失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 查看文档结果
const handleViewResult = async (task: DocumentTask) => {
  currentTask.value = task
  try {
    await documentStore.fetchTaskResult(task.taskId)
    resultVisible.value = true
  } catch (error: any) {
    ElMessage.error(`获取文档失败: ${error.message}`)
  }
}

// 导出文档
const handleExport = async (task: DocumentTask, format: 'html' | 'md') => {
  try {
    await documentStore.exportDocument(task.taskId, format)
    ElMessage.success('导出成功')
  } catch (error: any) {
    ElMessage.error(`导出失败: ${error.message}`)
  }
}

// 删除任务
const handleDelete = async (task: DocumentTask) => {
  try {
    await ElMessageBox.confirm('确定要删除这个任务吗？', '提示', {
      type: 'warning',
    })

    await documentStore.deleteTask(task.taskId)
    ElMessage.success('删除成功')
    await loadTaskList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(`删除失败: ${error.message}`)
    }
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.value.size = size
  pagination.value.current = 1
  loadTaskList()
}

const handleCurrentChange = (page: number) => {
  pagination.value.current = page
  loadTaskList()
}

// 跳转到创建页面
const goToCreate = () => {
  router.push('/document/create')
}

onMounted(() => {
  loadTaskList()
})
</script>

<style scoped>
.task-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.result-actions {
  margin-bottom: 16px;
}

.document-preview {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  background: white;
  min-height: 400px;
}
</style>
